<script setup>
import { ref, watch } from 'vue'
const msg = ref('ESports 模拟器')
const step = ref(0)
const userId = ref('')
const points = ref(0)
const users = ref([])
const userMap = {}
const ranks = ref([])
const deviceId = ref('')
const devices = ref([])
const deviceMap = {}
const startStep = ref(false)

const startTime = ref(new Date())
const endTime = ref(new Date())
const distance = ref(0)
const heartRate = ref(0)
const submitting = ref(false)
const sportRecords = ref([])
/** 用户 */
const getUser = () => {
  fetch(`/api-main/v1/user`).then(async (res) => {
    users.value = await res.json();
    for(var item of users.value){
      userMap[item.id] = item.nickName
    }
  })
}
getUser()
setInterval(() => {
  if(users.value.length == 0)
  {
    getUser()
  }
}, 5000)


watch(userId, async (newId) => {
  try {
    deviceId.value = ''
    const res = await fetch(`/api-main/v1/device/my/${newId}`)
    devices.value = await res.json()
    for(var item of devices.value){
      deviceMap[item.id] = item.description
    }
    step.value = 0
    await getPointsAsync(newId)
  } catch (error) {
    devices.value = []
    points.value = 0
  }
})
watch(deviceId, (newId) => {
  sportRecords.value = []
})

const getPointsAsync = async(id) => {
  const res = await fetch(`/api-main/v1/points/${id}`)
  points.value = (await res.json()).scores
}

setInterval(() => {
  if(deviceId.value.length > 0 && startStep.value){
    step.value += Math.round(Math.random()*100)
  }
}, 500)

setInterval(async () => {
  if(deviceId.value.length > 0){
    const res = await fetch(`/api-device/v1/step`, {
        method: "POST",
        body: JSON.stringify({
          deviceId: deviceId.value,
          count: step.value,
          date: new Date()
        }),
        headers: {
            "Content-type": "application/json"
        }
    })
    await getPointsAsync(userId.value)
  }
}, 2000)

setInterval(async () => {
  const res = await fetch(`/api-main/v1/rank`)
  let r = await res.json()
  r.sort((a, b) => b.count - a.count)
  ranks.value = r
}, 5000)

const sportType = ref('')
const sports = ref([])
const getSportType = () => {
  fetch(`/api-device/v1/sporttype`).then(async (res) => {
    sports.value = await res.json();
  })
}
getSportType()
setInterval(()=>{
  if(sports.value.length == 0){
    getSportType()
  }
}, 5000)

setInterval(()=>{
  if(deviceId.value != ''){
    fetch(`/api-device/v1/sport/withdevice/${deviceId.value}`).then(async(res) => {
      sportRecords.value = await res.json()
    })
  }
}, 5000)

const randomSport = () => {
  let et = new Date()
  let st = new Date(et.getTime() - (Math.round(20 + Math.random() * 40)) * 60 * 1000)
  endTime.value = et
  startTime.value = st
  distance.value = Math.round(3000 + Math.random() * 5000)
  heartRate.value = Math.round(100 + Math.random() * 50)
}

const submitSport = async () => {
  submitting.value = true
  try{
    const res = await fetch(`/api-device/v1/sport`, {
        method: "POST",
        body: JSON.stringify({
          deviceId: deviceId.value,
          startTime: startTime.value,
          endTime: endTime.value,
          description: sportType.value,
          distance: distance.value,
          heartRate: heartRate.value
        }),
        headers: {
            "Content-type": "application/json"
        }
    })
    alert("提交成功")
  }
  catch(e){
  }
  finally{
    submitting.value = false
  }
}

watch(sportType, (newType) => {
  distance.value = 0
  heartRate.value = 0
})


</script>

<template>
  <h1>{{ msg }}</h1>
  <h2>基本设置</h2>
  <div>用户: {{ userMap[userId] }}</div>
  <div>积分: {{ points }}</div>
  <select v-model="userId">
    <option disabled value="">Please select user</option>
    <option v-for="item in users" :value="item.id">{{item.nickName}}</option>
  </select>
  <div>设备: {{ deviceMap[deviceId] }}</div>
  <select v-model="deviceId">
    <option disabled value="">Please select device</option>
    <option v-for="item in devices" :value="item.id">{{item.description}}</option>
  </select>
  <br />
  <br />
  <h2>Steps</h2>
  <div class="flex">
    <section :style="{ width:'50%' }">
      <div>步数:</div>
      <input v-model="step">
      <button @click="startStep = !startStep">
        {{startStep ? "停止" : "启动"}}
      </button>
      <h5>说明： 每人每日步数超过10000 便可完成任务 +10分</h5>
    </section>
    <section>
      <div>步数排行榜:</div>
      <ul>
        <li v-for="item in ranks">{{item.nickName}}---{{item.count}} steps</li>
      </ul>
    </section>
  </div>
  
  <br />
  <br />
  <h2>Sports</h2>
  <div class="flex">
    <section :style="{ width:'50%' }">
      <div>运动类型: {{ sportType }}</div>
      <select v-model="sportType">
        <option disabled value="">Please select sport</option>
        <option v-for="item in sports" :value="item">{{item}}</option>
      </select>
      <div>开始时间: </div>
      <input v-model="startTime" type="datetime" readonly/>
      <div>结束时间: </div>
      <input v-model="endTime" type="datetime" readonly/>
      <div>距离: </div>
      <input v-model="distance" readonly/>
      <div>平均心率: </div>
      <input v-model="heartRate" readonly/>
      <div></div>
      <button @click="randomSport" :disabled="sportType==='' || deviceId =='' ">随机生成</button>
      <button @click="submitSport" :disabled="sportType==='' || deviceId =='' || heartRate == 0 || submitting">{{submitting ? "提交中...":"提交记录"}}</button>
      <h5>说明： 每日单项运动距离超过5000 便可完成任务 +10分</h5>
      <br/>
      <br/>
    </section>
    <section>
      <div>运动记录：</div>
      <ul>
        <li v-for="item in sportRecords">
          <div>类型：{{ item.description }} </div>
          <div>开始时间：{{item.startTime}} </div>
          <div>持续时间：{{item.duration}} </div>
          <div>运动距离：{{item.distance}}</div>
          <div>平均心率：{{item.heartRate}}</div>
        </li>
      </ul>
    </section>
  </div>
</template>